package com.sikaryofficial.qrcode.service.impl;

import com.sikaryofficial.qrcode.config.MinioConfig;
import com.sikaryofficial.qrcode.service.IDownloadService;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

/**
 * @author : qinjinyuan
 * @desc : 下载服务
 * @date : 2024/03/06 11:42
 */
@Service
@Slf4j
public class DownloadServiceImpl implements IDownloadService {
    @Autowired
    private MinioConfig minioConfig;
    @Autowired
    private MinioClient client;

    /**
     * 对象存储下载服务
     *
     * @param fileUri
     * @return
     */
    @Override
    public File downloadFile(String fileUri) throws Exception {
        // 由于系统保存的是 minioConfig.getBucketName() + "/" + fileName; 所以下面的地址需要去除桶
        fileUri = fileUri.replaceFirst(minioConfig.getBucketName() + "/", "");
        log.info("downloadFile:{}", fileUri);
        // 将输入流的内容复制到一个文件中
        File folder = new File("/data/tmp/minioDownload/");
        folder.mkdirs();
        File tmp = new File("/data/tmp/minioDownload/" + fileUri.substring(fileUri.lastIndexOf("/") + 1));
        try (InputStream inputStream = client.getObject(GetObjectArgs.builder()
                .bucket(minioConfig.getBucketName())
                .object(fileUri)
                .build())) {
            Files.copy(inputStream, tmp.toPath(), StandardCopyOption.REPLACE_EXISTING);
        }
        return tmp;
    }
}
